package io.geekidea.boot.generator.query;

import com.baomidou.mybatisplus.generator.config.querys.PostgreSqlQuery;

/**
 * PostgreSQL 14.4 测试通过
 *
 * @author geekidea
 * @date 2022/7/5
 **/
public class CustomPostgreSqlQuery extends PostgreSqlQuery {

    @Override
    public String tablesSql() {
        return "SELECT A.tablename, obj_description(B.oid) AS comments FROM pg_tables A, pg_class B WHERE A.schemaname='%s' AND A.tablename = B.relname";
    }

    @Override
    public String tableFieldsSql() {
        return "select TB.name,\n" +
                "       TB.type,\n" +
                "       TB.comment,\n" +
                "       TB.key,\n" +
                "       TB.length,\n" +
                "       TB.attnotnull,\n" +
                "       pg_get_expr(D.adbin, D.adrelid) AS default_value\n" +
                "from (\n" +
                "         SELECT A.attname                             AS name,\n" +
                "                format_type(A.atttypid, A.atttypmod)  AS type,\n" +
                "                col_description(A.attrelid, A.attnum) AS comment,\n" +
                "                (CASE\n" +
                "                     WHEN (SELECT COUNT(*)\n" +
                "                           FROM pg_constraint AS PC\n" +
                "                           WHERE A.attnum = PC.conkey[1]\n" +
                "                             AND PC.contype = 'p') > 0\n" +
                "                         THEN 'PRI'\n" +
                "                     ELSE '' END)                     AS key,\n" +
                "                ( CASE WHEN A.attlen > 0 THEN A.attlen ELSE A.atttypmod - 4 END ) AS length,\n" +
                "                A.attnotnull,\n" +
                "                A.attrelid,\n" +
                "                A.attnum\n" +
                "         FROM pg_class AS C,\n" +
                "              pg_attribute AS A\n" +
                "         WHERE A.attrelid = '%s'::regclass\n" +
                "           AND A.attrelid = C.oid\n" +
                "           AND A.attnum > 0\n" +
                "           AND NOT A.attisdropped\n" +
                "     ) TB\n" +
                "         LEFT JOIN pg_attrdef D ON (TB.attrelid, TB.attnum) = (D.adrelid, D.adnum)";
    }

    @Override
    public String[] fieldCustom() {
        return new String[]{"length", "attnotnull", "default_value"};
    }

}
